"""Definition of the CommunityOfPractice content type
"""

from zope.interface import implements, directlyProvides

from Products.Archetypes import atapi
from Products.ATContentTypes.content import folder
from Products.ATContentTypes.content import schemata
from Products.CMFPlone.utils import getToolByName

from utpocf.communityofpractice import communityofpracticeMessageFactory as _
from utpocf.communityofpractice.interfaces import ICommunityOfPractice
from utpocf.communityofpractice.config import PROJECTNAME
from collective.groupspace.roles.interfaces import ILocalGroupSpacePASRoles
from collective.groupspace.workflow.interfaces import ILocalGroupSpaceWorkflow


CommunityOfPracticeSchema = folder.ATFolderSchema.copy() + atapi.Schema((

    # -*- Your Archetypes field definitions here ... -*-

))

# Set storage on fields copied from ATFolderSchema, making sure
# they work well with the python bridge properties.

CommunityOfPracticeSchema['title'].storage = atapi.AnnotationStorage()
CommunityOfPracticeSchema['description'].storage = atapi.AnnotationStorage()

schemata.finalizeATCTSchema(CommunityOfPracticeSchema, folderish=True, moveDiscussion=False)

class CommunityOfPractice(folder.ATFolder):
    """A group for community of practice"""
    implements(ICommunityOfPractice,
               ILocalGroupSpacePASRoles,
               ILocalGroupSpaceWorkflow)

    portal_type = "CommunityOfPractice"
    schema = CommunityOfPracticeSchema

    title = atapi.ATFieldProperty('title')
    description = atapi.ATFieldProperty('description')

    user_roles = None
    group_roles = None


    def getRecent(self,limit=5):
        retval = []
        retval.extend(self.getRecentDiscussions(limit))
        retval.extend(self.getRecentContents(limit))
        retval.extend(self.getRecentNews(limit))
        return retval[:limit]

    def getRecentDiscussions(self,limit=5):
        discussionarea = getattr(self,'discussionarea','')
        if not discussionarea:
           return []

        return discussionarea.getRecent(limit)

    def getRecentContents(self,limit=5):
        sharingarea = getattr(self,'sharingarea','')
        if not sharingarea:
           return []

        return sharingarea.getRecent(limit)

    def getRecentNews(self,limit=5):
        news_events = getattr(self,'news_events','')
        if not news_events:
           return []

        catalog = getToolByName(self,'portal_catalog')
        path = '/'.join(news_events.getPhysicalPath())
        results = catalog(path=path,portal_type=('News Item','Event'),
                          sort_on='Date',
                          sort_order='descending',
                          sort_limit=limit)[:limit]

        return results 



atapi.registerType(CommunityOfPractice, PROJECTNAME)
